﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wicresoft.SMS.Common;
using System.Data.SqlClient;
namespace Wicresoft.SMS.Data
{
    public class sqlEmailDataAccess : IEmailDataAccess
    {
        private IConnectStringProvider _connParamProvider;

        public sqlEmailDataAccess(IConnectStringProvider configProvider)
        {
            _connParamProvider = configProvider;

        }

        public List<Email> GetUnsendMails()
        {
            try
            {
                using (var dbacc = new Entities(_connParamProvider.ConnectionString))
                {
                    var mails = dbacc.Email.Where(e => e.State == false).ToList<Email>();
                    return mails;
                }
            }
            catch (Exception ex)
            {
                Logger.Error("sqlEmailDataAccess.GetUnsendMails()" + ex.Message);
                return null;
            }
        }

        public void MarkEmailStateAsSent(IEnumerable<Email> emails)
        {
            if (emails == null)
            {
                Logger.Error("sqlEmailDataAccess.MarkEmailStateAsSent()" + " emails is NULL");
                return;
            }
            try
            {
                using (var dbacc = new Entities(_connParamProvider.ConnectionString))
                {
                    foreach (var item in emails)
                    {
                        var em = dbacc.Email.FirstOrDefault(e => e.ID == item.ID);
                        if (em != null)
                        {
                            em.State = item.State;
                            em.ModifyTime = item.ModifyTime;
                        }
                        else
                        {
                            Logger.Error(string.Format("sqlEmailDataAccess.MarkEmailStateAsSent() Cannot find the record {0}", item.ID));
                        }
                    }
                    dbacc.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                Logger.Error("sqlEmailDataAccess.MarkEmailStateAsSent()" + ex.Message);
            }
        }


        public bool SendEmail(List<Email> emails)
        {
            if (emails == null)
            {
                Logger.Error("sqlEmailDataAccess.SendEmail() " + " email is NULL");
                return false;
            }
            try
            {
                Logger.Debug("Entry SendEmail");
                using (var dbacc = new Entities(_connParamProvider.ConnectionString))
                {
                    foreach (var email in emails)
                    {
                        email.CreateTime = DateTime.Now;
                        email.State = false;
                        dbacc.AddToEmail(email);
                    }

                    dbacc.SaveChanges();
                    Logger.Debug("Leaving SendEmail");
                    return true;
                }
            }
            catch (Exception ex)
            {
                Logger.Error("sqlEmailDataAccess.SendEmail() " + ex.Message);
                return false;
            }

        }

        public bool SendSMSFromEmail(List<EmailInfo> emails)
        {
            try
            {
                using (var dbacc = new Entities(_connParamProvider.ConnectionString))
                {
                    List<Email> list = new List<Email>();
                    foreach (var item in emails)
                    {
                        
                        string[] temp = item.From.Split('<');
                        string from = temp[temp.Length - 1].Replace(">", "");
                        var user = dbacc.User.FirstOrDefault(u => u.Email == from && u.IsActive == 4);
                        if (user == null)
                        {
                            continue;
                        }
                        string to = "";
                        if (item.Subject.Trim() == "")
                        {
                            foreach (var contact in user.Contact)
                            {
                                foreach (var number in contact.Number)
                                {
                                    to += number.Number1 + ";";
                                }
                            }
                        }
                        else
                        {
                            item.Subject = item.Subject.Replace(',', ';');
                            string[] subs = item.Subject.Split(';');
                            foreach (var str in subs)
                            {
                                if (str.Trim() != "")
                                {
                                    Int64 r = 0;
                                    if (Int64.TryParse(str.Trim(),out r))
                                        to += str.Trim() + ";";
                                }
                            }
                        }
                        System.Data.Objects.ObjectParameter outs = new System.Data.Objects.ObjectParameter("outs", System.Data.DbType.Int32);
                        if (item.Body == null || to=="" )
                        {
                            continue;
                        }
                        dbacc.cp_send_sms(user.CIL, item.Body, to, outs);
                        int result = Convert.ToInt32(outs.Value);
                        if (result != 0)
                        {
                            string body = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">" +
                             "<html xmlns=\"http://www.w3.org/1999/xhtml\">" +
                             "<head>" +
                             "<title>FailedNotification.htm</title>" +
                             "<style type=\"text/css\">" +
                             ".style2leftcallcolor: #666666;font-size: medium;rightcall" +
                             ".style3leftcallfont-size: small;color: #333333;rightcall" +
                             "pleftcallmargin:6px;font-size:14px;rightcall" +
                             ".style4leftcallfont-family: \"Khmer UI\";font-size: 40px;rightcall" +
                             "</style>" +
                             "</head>" +
                             "<body style=\"text-align: left\">" +
                             "<p>亲爱的{0}:</p>" +
                             "<p>&nbsp;</p>" +
                             "<p>请检查以下联系人(邮件主题)是否正确，请确认其全部为电话号码，并且使用分号(英文)隔开。</p>" +
                             "<p>{1}</p>" +
                             "<p>短信内容为：</p>" +
                             "<p style=\"margin-left: 40px\" class=\"style3\"><span class=\"style4\">&quot;</span>{2}<span class=\"style4\">&quot;</span></p>" +
                             "<p>此邮件为系统自动发送，请勿回复，谢谢合作。</p>" +
                             "<p>&nbsp;</p>" +
                             "<p class=\"style2\">上海贝尔短信平台系统</p>" +
                             "<p class=\"style2\">{3}</p>" +
                             "</body>" +
                             "</html>";

                            Email email = new Email();
                            email.To = from;
                            email.Subject = "短信发送失败(通过邮件)";
                            email.Content = string.Format(body, user.NameEN, to, item.Body,DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                            list.Add(email);
                        }
                        SendEmail(list);
                    }
                    return true;
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
